package com.deam.imsdk.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.deam.imsdk.net.MessageObserver;
import com.deam.imsdk.net.TCPClient;
import com.deam.imsdk.net.TCPProtocol;
import com.deam.imsdk.utils.Constants;

/**
 * Created by Administrator on 2018/4/18.
 */

public class IMService extends Service implements MessageObserver, TCPProtocol {
    private final String TAG = "IMService";
    private TCPClient tcpClient;

    @Override
    public void onCreate() {
        super.onCreate();
        tcpClient = TCPClient.instance();
        tcpClient.connect(Constants.HostIp, Constants.IM_PORT, this);
        //注册消息拉取广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.IMS_BRPUSH_STRING);
        registerReceiver(new IMPushReceiver(), intentFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onUpdateConnect(int state) {
        switch (state) {
            case TCPClient.CONNECT_IN:
                System.out.println("正在连接");
                break;
            case TCPClient.CONNECT_OK:
                System.out.println("连接成功");
                break;
            case TCPClient.CONNECT_NO:
                System.out.println("已断开");
                try {
                    Thread.sleep(TCPClient.AGAIN_CONNECT_TIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                tcpClient.reConnect();
                break;
        }
        JSONObject json = new JSONObject();
        json.put(Constants.USER_ACTION, Constants.ACTION_CONNECT_UPDATE);
        json.put("state", state);
        doHandleMessage(json);
    }

    @Override
    public void doHandleMessage(JSONObject json) {
        Intent intent = new Intent();
        intent.setAction(Constants.IMS_BRPULL_STRING);
        intent.putExtra(Constants.IMS_MESSAGE, json.toJSONString());
        sendBroadcast(intent);
    }

    /**
     * 发送消息的广播接收器
     */
    class IMPushReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String im_msg = intent.getStringExtra(Constants.IMS_MESSAGE);
            if (im_msg != null) {
                tcpClient.sendMsg(JSONObject.parseObject(im_msg));
            }
        }
    }
}
